<template>
    <div id="main" onbeforeunload="checkLeave()">
        <div style="height:40px;line-height:40px;background: #eaeaea;">
            <i class="iconfont icon-close" @click='fnclose()'
                style="font-size: 2rem;color: rgb(84, 84, 84);padding-left: 17px;cursor:pointer;"></i>

            <div @click='fnSaveBlog()'
                style="cursor:pointer;height: 100%;float: right;width: 6rem;text-align: center;color: white;background:linear-gradient(45deg, #9000ff, #5e00ff)">
                发布</div>
            <div @click='fnisTop()' :style="isTop=='开'?'color: white;background: rgb(64, 64, 64);':''"
                style="cursor:pointer;height: 100%;float: right;width: 7rem;text-align: center;color: #474844;background: #dfe0dc; user-select:none;">
                是否置顶({{isTop}})</div>
            <div @click='fnisIndex()' :style="isIndex=='开'?'':'color: #474844;background: #dfe0dc; user-select:none;'"
                style="cursor:pointer;height: 100%;float: right;width: 7rem;text-align: center;color: white;background: rgb(64, 64, 64);">
                首页可见({{isIndex}})</div>
        </div>

        <el-input placeholder="请输入内容" v-model="title">
            <template slot="prepend" style="color: #ff6b6b;">标题</template>
        </el-input>
        <el-input placeholder="请输入图片地址(默认为上传的第一张图片)" v-model="bgImg">
            <template slot="prepend" style="color: #ff6b6b;">封面</template>
        </el-input>
        <div style="height: 40px;position: relative;">
            <span class="upLoad">上传附件</span>
            <el-upload class="upload-demo" :action="uploadUrl" :on-change="handleChange" :file-list="fileList"
                style="opacity: 0;top: 5px;position: absolute;height: 40px;opcity:0;" :on-success='uploadSuccess'
                :on-progress='uploadProgress'>
                <el-button size="small" type="primary">上传附件</el-button>
            </el-upload>
            <span class="progress" :style="'width: calc('+progress+'% - 70px);'"
                v-if='showProgress&&progress > 5'>{{Math.floor(progress)}}%</span>
            <span class="upFileUrl">{{upFileUrl}} <i v-if='upFileUrl' class="iconfont icon-close" @click='clearUpfile()'
                    style="cursor:pointer;float: right;height: 40px;line-height: 40px;font-size: 31px;position: absolute;right: 0;"></i>
            </span>
        </div>
        <div style="height: 40px;position: relative;display: flex;">
            <span class="upLoad" style="background-color: rgb(245, 247, 250);cursor: pointer;background: #696969;" @click='fnaddBlogClass()'>增加分类</span>
            <el-select placeholder="请选择博客分类" style="width: 95%;display: inline-block;" v-model="blogClass">
                <el-option :label="blogclass.className" :value="blogclass.className" v-for='blogclass in blogClassList'
                    :key="blogclass.id">
                    <span style="float: left; font-size: 13px">{{blogclass.className}}</span>
                    <span class='iconfont icon-close' style="float:right;color: rgb(255, 255, 255);font-size: 28px;"
                        @click.prevent='fnDelete(blogclass.className)'></span>
                </el-option>
            </el-select>
        </div>

        <div style="height: 90%;overflow: scroll;">
            <mavon-editor v-model="markdownValue" :ishljs="true" style="height: 100%;" ref=md @imgAdd="$imgAdd"
                :toolbarsBackground="'#5d5d5d'" :previewBackground="'#5d5d5d'" />
        </div>
        <!-- <div class="btn hvr-hang" ><i class="iconfont icon-baocun"></i></div> -->
        <!-- <a href="#" data-title="Awesome Button" @mousemove="move(this)" @mouseleave='leave(this)' @mousedown="down()" @mouseup="up()"></a> -->
        <!-- <div @click='fnSaveBlog()' style="cursor:pointer">
            
        </div> -->
    </div>
</template>


<script>
import { mapGetters, mapActions } from "vuex";
import auth from "../../api/auth";
import blog from "../../api/blog";
import Header from "../../components/Header/Header";
import Footer from "../../components/Footer/Footer";
// import Auth from "../../helpers/loginAnimate.js";
import lottieSave from '../../components/lottie/lottie-save'
import axios from 'axios'
export default {
    name: "index",
    components: {
        Header,
        Footer,
        lottieSave
    },
    data() {
        return {
            title: '',
            markdownValue: '',
            blogClass: '',
            blogClassList: [],
            interval: '',
            bgImg: '',
            attach: '',
            fileList: [],
            uploadUrl: blog.upload(),//请求的地址
            progress: 0,
            showProgress: false,
            upFileUrl: '',//请求成功的地址
            isIndex: '开',
            isTop: '关'
        };
    },
    created() {
        this.findBlogClass()
        this.autoSave()
        console.log('created')
        // window.onbeforeunload=function(e){
        // 　　var e = window.event||e;  
        // 　　e.returnValue=("确定离开当前页面吗？");
        // } 
    },
    mounted() {
        console.log('mounted')
        this.initData()
        // window.onbeforeunload=function(e){     
        // 　　var e = window.event||e;  
        // 　　e.returnValue=("确定离开当前页面吗？");
        //     if(event.clientX>document.body.clientWidth && event.clientY < 0 || event.altKey){ 
        //         alert("你关闭了浏览器"); 
        //     }else{ 
        //         alert("你正在刷新页面"); 
        //     }
        // } 
    },
    methods: {
        ...mapActions(["login", "checkLogin", "logout", "getPermissions"]),
        fnaddBlogClass(){
            this.$prompt('请输入博客分类', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(({ value }) => {
                   this.addBlogClass(value)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '取消输入'
                });       
            });
        },
        async addBlogClass(className){
            try {
                let res = await blog.addBlogClass(className)
                if (res.success) {
                    this.$message.success({ message: '增加成功' })
                    setTimeout(() => {
                        this.findBlogClass()
                    }, 1500)
                } else {
                    this.$message.error({ message: '删除失败' })
                }
            } catch (err) {
                console.log(err)
                this.$message.error({ message: err.errorMsg })
            }
        },

        fnDelete(className) {
            this.$confirm('此操作将删除分类[' + className + '], 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteBlogClass(className)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        async deleteBlogClass(className) {
            try {
                let res = await blog.deleteBlogClass(className)
                if (res.success) {
                    this.$message.success({ message: '删除成功' })
                    this.blogClass = ''
                    setTimeout(() => {
                        this.findBlogClass()
                    }, 1500)
                } else {
                    this.$message.error({ message: '删除失败' })
                }
            } catch (err) {
                console.log(err)
                this.$message.error({ message: err.errorMsg })
            }
        },

        fnisIndex() {
            if (this.isIndex == '开') {
                this.isIndex = '关'
            } else {
                this.isIndex = '开'
            }
        },
        fnisTop() {
            if (this.isTop == '开') {
                this.isTop = '关'
            } else {
                this.isTop = '开'
            }
        },
        clearUpfile() {
            this.upFileUrl = ''
        },
        uploadSuccess(e) {//上传附件
            console.log(e)
            this.showProgress = false

            if (e.success) {
                this.upFileUrl = e.data
            } else {
                this.$message.error('上传失败')
            }
        },
        uploadProgress(e) {
            this.showProgress = true
            this.progress = e.percent
        },
        handleChange(file, fileList) {
            // this.fileList = fileList.slice(-3);
        },
        fnclose() {
            window.close();
        },
        async fnSaveBlog() {
            console.log(this.blogClass)
            try {
                if (this.title == '' || this.markdownValue == '' || this.blogClass == '') return this.$message({ message: '输入内容不可为空', type: 'warning' })
                let isTop = this.isTop == '开' ? 1 : 0
                let isIndex = this.isIndex == '开' ? 1 : 0
                let res = await blog.saveBlog(this.user.name, this.title, this.markdownValue, this.blogClass, this.bgImg, this.upFileUrl, isTop, isIndex)
                console.log(res)
                if (res.success) {
                    this.$message({ message: '保存成功', type: 'success' })
                    //清空数据
                    localStorage.removeItem('blogSave')
                    //clearInterval(this.interval)
                    this.title = ''
                    this.markdownValue = ''
                    this.blogClass = ''
                    this.upFileUrl = ''
                    this.bgImg = ''
                    setTimeout(() => {
                        window.close();
                    }, 1000)
                }
            } catch (err) {
                console.log(err)
                this.$message.error({ message: err.errorMsg })
            }
        },
        //查找博客分类方法
        async findBlogClass() {
            let res = await blog.findBlogClass()
            if (res.success) {
                this.blogClassList = res.data
            }
        },
        //初始化数据
        initData() {
            if (localStorage.getItem('blogSave')) {
                let blogSave2 = JSON.parse(localStorage.getItem('blogSave'))
                this.title = blogSave2.title
                this.blogClass = blogSave2.blogClass
                this.markdownValue = blogSave2.body
                this.upFileUrl = blogSave2.upFileUrl
                this.bgImg = blogSave2.bgImg
            }
        },
        autoSave() {
            this.interval = setInterval(() => {
                let blogSave = {}
                blogSave.title = this.title //自动保存标题
                blogSave.blogClass = this.blogClass//自动保存分类
                blogSave.body = this.markdownValue
                blogSave.upFileUrl = this.upFileUrl
                blogSave.bgImg = this.bgImg
                localStorage.setItem('blogSave', JSON.stringify(blogSave))//把用户信息存到localStorage
            }, 10000)

        },
        checkLeave() {
            event.returnValue = "确定离开当前页面吗？";
        },
        // 绑定@imgAdd event

        $imgAdd(pos, $file) {
            //上传图片接口
            console.log($file)
            var formdata = new FormData();
            formdata.append('file', $file);
            blog.upImg(formdata).then(res => {
                if (res.success) {
                    this.$message({ message: '图片上传成功', type: 'success' })
                    if (!this.bgImg) {
                        this.bgImg = res.data
                    }
                    this.$refs.md.$img2Url(pos, res.data);
                } else {
                    this.$message.error({ message: '上传图片失败' })
                }
            })
        },
    },
    computed: {
        ...mapGetters(["isLogin", "user"])
    }
};
</script>
<style lang="less" scoped>
@import "../../assets/css/auth.css";

::-webkit-scrollbar-thumb {
    background: white !important;
}
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
    background-color: white !important;
}
.upLoad {
    height: 40px;
    display: inline-block;
    background: #696969;
    width: 70px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 13px;
    color: #ffffff;
}
.progress {
    height: 40px;
    display: inline-block;
    width: calc(100% - 70px);
    background: #5252523d;
    position: absolute;
    top: 0;
    margin-left: 70px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.upFileUrl {
    height: 40px;
    display: inline-block;
    width: calc(90% - 70px);
    position: absolute;
    top: 0;
    margin-left: 70px;
    display: flex;
    align-items: center;
    padding-left: 17px;
}
a {
    position: relative;
    display: inline-block;
    padding: 1.2em 2em;
    text-decoration: none;
    text-align: center;
    cursor: pointer;
    user-select: none;
    color: white;

    &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
        right: 0;
        background: linear-gradient(135deg, #6e8efb, #a777e3);
        border-radius: 4px;
        transition: box-shadow 0.5s ease, transform 0.2s ease;
        will-change: transform;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        transform: translateY(var(--ty, 0)) rotateX(var(--rx, 0))
            rotateY(var(--ry, 0)) translateZ(var(--tz, -12px));
    }

    &:hover::before {
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
    }

    &::after {
        position: relative;
        display: inline-block;
        content: attr(data-title);
        transition: transform 0.2s ease;
        font-weight: bold;
        letter-spacing: 0.01em;
        will-change: transform;
        transform: translateY(var(--ty, 0)) rotateX(var(--rx, 0))
            rotateY(var(--ry, 0));
    }
}

#main {
    height: 100vh;
}
.v-note-op {
    border: 1px solid #e6e6e6 !important;
    box-shadow: none !important;
}
.btn {
    position: fixed;
    top: 87%;
    right: 3%;
    z-index: 9999;
    height: 50px;
    width: 50px;
    background: #f97575;
    border-radius: 50%;
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: all 0.3s;
    &:hover {
        background: #ff6262;
        box-shadow: 0 0 6px 1px #ff8888;
        transition: all 0.3s;
    }
}
.markdown-body img {
    max-height: 40rem;
}
</style>

